﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using EyesBaby.Update;

namespace WinUpdate
{
    public partial class frmEyesBabyUpdate : Form
    {
        // 当前配置文件路径
        string curConfigPath = Application.StartupPath + "\\CurrentInfo.config";
        static string connectString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Application.StartupPath + "\\" + System.Configuration.ConfigurationSettings.AppSettings["logDatabasePath"];
        LogHelper.BLL.Log bllLog = new LogHelper.BLL.Log(connectString);

        public frmEyesBabyUpdate()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 调用更新
        /// </summary>
        private void CallUpdate()
        {
            string updatexmlpath = System.Configuration.ConfigurationSettings.AppSettings["updateXmlPath"];
            LogHelper.Model.Log modLog = new LogHelper.Model.Log();
            // 自动更新对象
            AutoUpdate autoUpdate = new AutoUpdate();
            // 当前版本操作对象
            CurrentVesionHelper currentVesion = new CurrentVesionHelper(curConfigPath);
            try
            {
                // 更新文件操作对象
                UpdateXmlHelper updateXml = new UpdateXmlHelper(updatexmlpath);

                string oldVesion = currentVesion.CurrentVesion;
                string newVesion = updateXml.Vesion;
                string newDownURL = updateXml.DownURL;
                // 判断是否有新版本
                bool b = autoUpdate.IsNewVesion(newVesion, oldVesion);

                if (b)
                {
                    string filename = newDownURL.Substring(newDownURL.LastIndexOf('/') + 1);
                    string savePath = Application.StartupPath + "/update/" + filename;
                    SetValue("正在下载新版本……", 10);
                    if (autoUpdate.DownNewEdition(newDownURL, savePath))
                    {
                        string installDir = currentVesion.InstallDir = Application.StartupPath;
                        string programName = currentVesion.ProgramName;

                        string error = string.Empty;
                        string zipfilepath = savePath;
                        string unzipdir = Application.StartupPath + "\\update\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                        SetValue("正在解压文件包……", 20);
                        // 解压文件包
                        clsZip zip = new clsZip();
                        zip.UnZipFile(zipfilepath, unzipdir, out error);
                        SetValue("正在关闭程序……", 10);
                        // 关闭程序
                        System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcessesByName(programName);
                        foreach (System.Diagnostics.Process p in ps)
                        {
                            p.Kill();
                        }
                        SetValue("正在覆盖原安装程序……", 20);
                        #region 覆盖原安装程序
                        // 休息1秒
                        System.Threading.Thread.Sleep(1000);
                        string installPath = installDir + "\\" + programName;
                        //if (System.IO.Directory.Exists(installPath))
                        //{
                        //    // 先删除原安装路径
                        //    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(installPath);
                        //     dir.Delete(true);
                        //    //System.IO.Directory.Delete(installPath, true);
                        //}
                        //// 休息3秒
                        //System.Threading.Thread.Sleep(5000);
                        // 再将新版本复制到原安装目录
                        CopyFolder copy = new CopyFolder();
                        copy.CopyDirectory(unzipdir, installDir);
                        //System.IO.Directory.Move(unzipdir, installDir);

                        #endregion
                        string exepath = "EyesBaby.exe";
                        // 休息3秒
                        System.Threading.Thread.Sleep(3000);
                        string startpath = installPath + "\\" + exepath;
                        SetValue("记录新版本……", 20);

                        // 记录新版本到CurrentInfo.config
                        currentVesion.CurrentVesion = newVesion;
                        currentVesion.UpdateDate = DateTime.Now.ToShortDateString();
                        currentVesion.UpdateVesion();

                        modLog.Content = "更新成功--新版本号:" + newVesion;
                        //MessageBox.Show("更新成功！");
                        SetValue("重启程序……", 20);
                        // 重启程序
                        System.Diagnostics.Process.Start(startpath);

                    }
                    else
                    {
                        modLog.Content = "下载最新版本失败";
                        MessageBox.Show("下载最新版本失败!");
                    }
                }
                else
                    modLog.Content = "没有发现新版本";
                modLog.Title = "调用更新服务";
                modLog.CreateDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                bllLog.Add(modLog);
            }
            catch
            {
                // 有任何异常，退出更新
                this.Close();
            }
        }

        /// <summary>
        /// 设置加载时间值
        /// </summary>
        /// <param name="text"></param>
        /// <param name="value"></param>
        private void SetValue(string text, int value)
        {
            // 更新进度
            for (int i = 1; i <= value; i++)
            {
                bkgWorker.ReportProgress(1, text);
                System.Threading.Thread.Sleep(10);
            }
        }

        private void frmEyesBabyUpdate_Load(object sender, EventArgs e)
        {

            // 判断是否有新版本
            AutoUpdate autoUpdate = new AutoUpdate();
            CurrentVesionHelper currentVesion = new CurrentVesionHelper(curConfigPath);

            string updatexmlpath = System.Configuration.ConfigurationSettings.AppSettings["updateXmlPath"];
            try
            {
                UpdateXmlHelper updateXml = new UpdateXmlHelper(updatexmlpath);
                string oldVesion = currentVesion.CurrentVesion;
                string newVesion = updateXml.Vesion;
                string newDownURL = updateXml.DownURL;
                bool b = autoUpdate.IsNewVesion(newVesion, oldVesion);
                if (b)
                {
                    if (MessageBox.Show("有新版本，是否下载更新？", "EyesBaby更新提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        bkgWorker.RunWorkerAsync();
                    else
                        this.Close();
                }
                else
                    this.Close();
            }
            catch
            { 
                // 任何异常，关闭更新
                this.Close();
            }
        }

        /// <summary>
        /// 执行工作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // 调用更新
            CallUpdate();
        }

        /// <summary>
        /// 操作进程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblMsg.Text = e.UserState.ToString();
            prgUpdate.Value += e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Close();
        }
    }
}
